<template>
  <div class="category-management-container">
    <!-- 筛选区和设置图标同一行 -->
    <div class="filter-bar">
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索类别名称"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          style="width: 250px; margin-left: 10px;"
          size="small"
        >
        </el-input>

        <el-button type="primary" style="margin-left: 10px;" size="small" @click="handleSearch">查询</el-button>
        <el-button type="default" size="small" @click="resetSearch">重置</el-button>
        <el-button type="primary" size="small" @click="handleAdd">添加</el-button>
      </div>
      <div class="filter-setting-icon">
        <el-popover
          placement="bottom-end"
          width="220"
          trigger="click"
          v-model="showColumnSetting"
        >
          <div v-for="col in columns" :key="col.key">
            <el-checkbox v-model="col.visible">{{ col.label }}</el-checkbox>
          </div>
          <div style="text-align: right;">
            <el-button type="text" size="mini" @click="resetColumns">重置</el-button>
          </div>
          <i
            class="el-icon-setting"
            slot="reference"
            style="cursor: pointer; font-size: 20px; margin-left: 10px;"
          ></i>
        </el-popover>
      </div>
    </div>

    <!-- 数据表格 - 移动端滚动容器 -->
    <div class="table-wrapper">
      <el-table
        :data="tableData"
        style="width: 100%;"
        border
        v-loading="loading"
      >
      <el-table-column v-if="getColumnVisible('index')"
        type="index"
        label="序号"
        width="80"
        align="center">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('category_name')"
        prop="category_name"
        label="类别名称"
        min-width="200">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('create_time')"
        prop="create_time"
        label="创建时间"
        width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column v-if="getColumnVisible('operate')"
        label="操作"
        width="150"
        align="center"
        fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <PageCom :total="totalData" :pageSize="pageSize" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" :currentPage="currentPage"></PageCom>
    </div>

    <!-- 添加/编辑类别弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="resetDialogForm"
    >
      <el-form :model="dialogForm" :rules="dialogFormRules" ref="dialogForm" label-width="100px">
        <el-form-item label="类别名称" prop="category_name">
          <el-input v-model="dialogForm.category_name" placeholder="请输入类别名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDialogForm" :loading="submitLoading">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryList, categoryAdd, categoryEdit, categoryDelete } from '@/api/contract'
import PageCom from '@/components/PageCom.vue';

export default {
  name: 'CategoryManagementView',
  components: {
    PageCom,
  },
  data() {
    return {
      searchQuery: '',
      loading: false,
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      tableData: [],
      totalData: 0,
      dialogVisible: false,
      dialogTitle: '添加类别',
      submitLoading: false,
      dialogForm: {
        id: null,
        category_name: ''
      },
      dialogFormRules: {
        category_name: [
          { required: true, message: '请输入类别名称', trigger: 'blur' },
          { min: 1, max: 50, message: '类别名称长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      // 字段显示控制配置
      columns: [
        { key: 'index', label: '序号', visible: true },
        { key: 'category_name', label: '类别名称', visible: true },
        { key: 'create_time', label: '创建时间', visible: true },
        { key: 'operate', label: '操作', visible: true }
      ],
      showColumnSetting: false,
    }
  },
  created() {
    this.fetchCategoryList()
  },
  methods: {
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '-';
      
      let date;
      if (typeof timestamp === 'string') {
        date = new Date(timestamp);
      } else if (timestamp.toString().length === 10) {
        date = new Date(timestamp * 1000);
      } else if (timestamp.toString().length === 13) {
        date = new Date(timestamp);
      } else {
        date = new Date(timestamp);
      }
      
      if (isNaN(date.getTime())) {
        return '-';
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 获取类别列表
    async fetchCategoryList() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery || ''
        }
        const response = await getCategoryList(params)
        if (response.data.code === 200) {
          const categoryData = response.data.data
          if(categoryData.total === 0){
            this.$message.warning('暂无数据');
          }
          this.tableData = categoryData.data || []
          this.totalData = categoryData.total || 0
        } else {
          this.$message.error(response.data.msg || response.data.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取类别列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchCategoryList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchCategoryList()
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchCategoryList()
    },
    resetSearch() {
      this.searchQuery = ''
      this.currentPage = 1
      this.fetchCategoryList()
    },
    handleAdd() {
      this.dialogTitle = '添加类别'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dialogForm.resetFields()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑类别'
      this.dialogVisible = true
      this.$nextTick(() => {
        // 填充表单数据
        this.dialogForm = {
          id: row.id,
          category_name: row.category_name
        }
      })
    },
    handleDelete(row) {
      this.$confirm(`确定删除类别 "${row.category_name}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await categoryDelete(row.id)
          if (response.data.code === 200) {
            this.$message.success('删除成功')
            this.fetchCategoryList() // 刷新列表
          } else {
            this.$message.error(response.data.msg || response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除类别失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 用户取消删除
      })
    },
    submitDialogForm() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            const params = {
              category_name: this.dialogForm.category_name
            }
            
            // 如果是编辑，添加id
            if (this.dialogForm.id) {
              params.id = this.dialogForm.id
            }
            
            let response
            if (this.dialogForm.id) {
              // 编辑
              response = await categoryEdit(params)
            } else {
              // 添加
              response = await categoryAdd(params)
            }

            if (response.data.code === 200) {
              this.$message.success(this.dialogForm.id ? '编辑成功' : '添加成功')
              this.dialogVisible = false
              this.fetchCategoryList() // 刷新列表
            } else {
              this.$message.error(response.data.msg || response.data.message || (this.dialogForm.id ? '编辑失败' : '添加失败'))
            }
          } catch (error) {
            console.error(this.dialogForm.id ? '编辑类别失败:' : '添加类别失败:', error)
            this.$message.error(this.dialogForm.id ? '编辑失败' : '添加失败')
          } finally {
            this.submitLoading = false
          }
        } else {
          return false
        }
      })
    },
    resetDialogForm() {
      this.dialogForm = {
        id: null,
        category_name: ''
      }
      if (this.$refs.dialogForm) {
        this.$refs.dialogForm.resetFields()
      }
    },
    getColumnVisible(key) {
      const col = this.columns.find(c => c.key === key);
      return col ? col.visible : false;
    },
    resetColumns() {
      this.columns.forEach(col => col.visible = true);
    },
  }
}
</script>

<style scoped>
/* 表格滚动容器样式 */
.table-wrapper {
  margin-top: 20px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

/* 移动端响应式设计 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-container {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    margin-bottom: 10px;
  }
  
  .filter-container .el-input,
  .filter-container .el-button {
    margin-left: 0 !important;
    margin-right: 10px;
    margin-bottom: 10px;
    width: 100%;
  }
  
  .filter-setting-icon {
    align-self: flex-end;
  }
  
  .table-wrapper {
    -webkit-overflow-scrolling: touch;
  }
  
  .el-table {
    font-size: 12px;
    width: 450px;
  }
  
  .pagination-container {
    margin-top: 15px;
  }
}
.category-management-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px - 20px);
  box-sizing: border-box;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
}

.filter-setting-icon {
  display: flex;
  align-items: center;
  height: 32px;
}

/* 表格样式 */
::v-deep .el-table {
  border: 1px solid #EBEEF5;
}

::v-deep .el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

::v-deep .el-table td, ::v-deep .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

::v-deep .el-table th:last-child,
::v-deep .el-table td:last-child {
  border-right: none;
}

::v-deep .el-table::after, ::v-deep .el-table::before {
  background-color: transparent;
}

.dialog-footer {
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

::v-deep .el-input__inner {
  background-color: white !important;
}
</style>


